/**
 * Copyright &copy; 2012-2016 <a href="https://istep.lczyfz.com">Istep</a> All rights reserved.
 */
package com.lczyfz.istep.modules.scene.service;

import com.lczyfz.istep.common.constants.DelFlag;
import com.lczyfz.istep.common.constants.SceneConstants;
import com.lczyfz.istep.common.enums.JobIsFactoryType;
import com.lczyfz.istep.common.enums.JobStatus;
import com.lczyfz.istep.common.persistence.Page;
import com.lczyfz.istep.common.service.CrudService;
import com.lczyfz.istep.common.utils.IdGen;
import com.lczyfz.istep.common.utils.domain.Demo;
import com.lczyfz.istep.modules.openstack.api.nova.impl.FlavorsImpl;
import com.lczyfz.istep.modules.openstack.api.nova.impl.VirtualMachineImpl;
import com.lczyfz.istep.modules.openstack.api.nova.impl.serveraction.ConsolePartImpl;
import com.lczyfz.istep.modules.openstack.api.nova.model.Flavor;
import com.lczyfz.istep.modules.openstack.api.nova.model.Server;
import com.lczyfz.istep.modules.openstack.api.nova.model.serveraction.ConsoleIndex;
import com.lczyfz.istep.modules.openstack.api.nova.model.serveraction.ConsoleType;
import com.lczyfz.istep.modules.scene.dao.SceneCtfEnvironmentDao;
import com.lczyfz.istep.modules.scene.entity.*;
import com.lczyfz.istep.modules.sys.entity.ScheduleJob;
import com.lczyfz.istep.modules.sys.service.ScheduleJobService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * CTF实验环境Service
 * @author dh
 * @version 2017-05-15
 */
@Service
@Transactional(readOnly = true)
public class SceneCtfEnvironmentService extends CrudService<SceneCtfEnvironmentDao, SceneCtfEnvironment> {
	@Autowired
	private SceneNetworkService sceneNetworkService;
	@Autowired
	private SceneRouterService sceneRouterService;
	@Autowired
	private SceneSecurityGroupService sceneSecurityGroupService;
	@Autowired
	private SceneSecurityGroupRuleService sceneSecurityGroupRuleService;
	@Autowired
	private SceneSubnetService sceneSubnetService;
	@Autowired
	private SceneVmTemplateService sceneVmTemplateService;
	@Autowired
	private SceneVmTypeService sceneVmTypeService;
	@Autowired
	private ScenePortService scenePortService;
	@Autowired
	private SceneCtfEnvironmentInstanceService sceneCtfEnvironmentInstanceService;
	@Autowired
	private ScheduleJobService scheduleJobService;
	public SceneCtfEnvironment get(String id) {
		return super.get(id);
	}
	
	public List<SceneCtfEnvironment> findList(SceneCtfEnvironment sceneCtfEnvironment) {
		return super.findList(sceneCtfEnvironment);
	}
	
	public Page<SceneCtfEnvironment> findPage(Page<SceneCtfEnvironment> page, SceneCtfEnvironment sceneCtfEnvironment) {
		return super.findPage(page, sceneCtfEnvironment);
	}
	
	@Transactional(readOnly = false)
	public void save(SceneCtfEnvironment sceneCtfEnvironment) {
		super.save(sceneCtfEnvironment);
	}
	
	@Transactional(readOnly = false)
	public void delete(SceneCtfEnvironment sceneCtfEnvironment) {
		super.delete(sceneCtfEnvironment);
	}
	@Transactional(readOnly = false)
	public void  evmNetworkInsert (String info1,String info2)
	{
		dao.evmNetworkInsert(info1, info2);
	}
	@Transactional(readOnly = false)
	public void  evmRouterInsert (String info1,String info2)
	{
		dao.evmRouterInsert(info1, info2);
	}
	@Transactional(readOnly = false)
	public void  evmSgInsert (String info1,String info2)
	{
		dao.evmSgInsert(info1, info2);
	}
	@Transactional(readOnly = false)
	public void  evmVmInsert (String info1,String info2,String info3,String info4,String info5)
	{
		dao.evmVmInsert(info1, info2, info3, info4, info5);
	}
	//删除实验环境相关
	@Transactional(readOnly = false)
	public void evmRelateDelete(SceneCtfEnvironment sceneCtfEnvironment){
		logger.debug("dingh===删除实验环境相关");

		List<SceneEnvironmentRelate> networkList= dao.findEvmNetworkList(sceneCtfEnvironment);
		List<SceneEnvironmentRelate> routerList= dao.findEvmRouterList(sceneCtfEnvironment);
		List<SceneEnvironmentRelate> vmList= dao.findEvmVmList(sceneCtfEnvironment);
		List<SceneEnvironmentRelate> sgList= dao.findEvmSecurityGroupList( sceneCtfEnvironment);

		logger.debug("dingh===routerList="+routerList.size());

		for(SceneEnvironmentRelate sr:routerList){
			logger.debug("dingh===routerList="+sr.getRouterId());

			SceneRouter sceneRouter=new SceneRouter();
			sceneRouter.setId(sr.getRouterId());
			sceneRouterService.delete(sceneRouter);
			dao.routerInterfaceDelete(sr);
			sceneRouterService.deleteRouterTable(sr.getRouterId());

			SceneFirewall sceneFirewall=sceneRouterService.getRouterFirewall(sr.getRouterId());
			if(sceneFirewall!=null&&sceneFirewall.getId()!=null&&!sceneFirewall.getId().equals(""))
			{
				sceneRouterService.deleteFirewallRule(sceneFirewall.getId());
				sceneRouterService.deleteFirewall(sceneFirewall.getId());
			}
			sceneRouterService.deleteRouterFirewall(sr.getRouterId());

		}
		for (SceneEnvironmentRelate sr:networkList){
			SceneNetwork sceneNetwork=new SceneNetwork();
			sceneNetwork.setId(sr.getNetworkId());
			sceneNetworkService.delete(sceneNetwork);
			dao.subnetDelete(sr);

		}
//		for (SceneEnvironmentRelate sr:vmList){
//			SceneVmTemplate sceneVmTemplate=new SceneVmTemplate();
//			sceneVmTemplate.setId(sr.getVmTemplateId());
//			sceneVmTemplateService.delete(sceneVmTemplate);
//		}
		for(SceneEnvironmentRelate sr:sgList){
			SceneSecurityGroup sceneSecurityGroup=new SceneSecurityGroup();
			sceneSecurityGroup.setId(sr.getSecurityGroupId());
			sceneSecurityGroupService.delete(sceneSecurityGroup);
		}
		dao.evmNetworkDelete(sceneCtfEnvironment);
		dao.evmVmDelete(sceneCtfEnvironment);
		dao.evmRouterDelete(sceneCtfEnvironment);
		dao.evmSgDelete(sceneCtfEnvironment);
		logger.debug("dingh===删除ctf实验环境相关完成");

	}
	/**
	 *创建实例
	 */
	@Transactional(readOnly = false)
	public void createCtfInstance(SceneCtfEnvironment sceneCtfEnvironment,SceneCtfEnvironmentInstance sceneCtfEnvironmentInstance) throws RuntimeException,Exception{

		System.err.println(sceneCtfEnvironmentInstance.toString());

		//生成实验环境
		sceneCtfEnvironmentInstanceService.save(sceneCtfEnvironmentInstance);
		logger.debug("dingh===ctf实例id=插入=" + sceneCtfEnvironmentInstance.getId());


		List<SceneEnvironmentInstanceOs> instanceVmList=new ArrayList<>();
		ArrayList<String> firewallRuleIdList=new ArrayList<>();

		Map<String ,String > subnetMap=new HashMap<>();
		Map<String ,String > networkMap=new HashMap<>();
		Map<String ,String > vmMap=new HashMap<>();
		Map<String ,String > sgMap=new HashMap<>();


		//虚拟机
		List<SceneVmTemplate> sceneVmTemplateList=sceneVmTemplateService.findVMListByEnvironmentId(DelFlag.DEL_FLAG_NORMAL, sceneCtfEnvironment.getId());
		logger.debug("dingh===sceneVmTemplateList=" + sceneVmTemplateList.size());
		try{
	/**
			//创建网络
			//保存子网
			List<SceneNetwork> sceneNetworkList=sceneNetworkService.findNetworkListByEnvironmentId(DelFlag.DEL_FLAG_NORMAL,sceneCtfEnvironment.getId());
			logger.debug("dingh===sceneNetworkList="+sceneNetworkList.size());
			for(SceneNetwork sceneNetwork:sceneNetworkList) {
				logger.debug("dingh===sceneNetwork=" + sceneNetwork.getNetworkName());

				NetworksImpl networkDemo=new NetworksImpl();
				Network nw=new Network();
				nw.setName(sceneNetwork.getNetworkName());
				logger.debug("dingh===NetworkName" + sceneNetwork.getNetworkName());

				Network nwCreat=networkDemo.createNetwork(nw);
				logger.debug("dingh===虚拟机-网络id=" + nwCreat.getId());

//				instanceNetworkList.add(nwCreat.getId());
				networkMap.put(sceneNetwork.getId(), nwCreat.getId());
//				logger.debug("networkId=== [{}]", nwCreat.getId()+" "+instanceNetworkList.get(0));

				List<SceneSubnet> sceneSubnetList=sceneSubnetService.findSubnetListByNetworkId(sceneNetwork);
				logger.debug("dingh===sceneSubnetList="+sceneSubnetList.size());

				for(SceneSubnet sceneSubnet:sceneSubnetList)
				{
					logger.debug("dingh===[{}],=[{}],=[{}],=[{}],",sceneSubnet.getSubnetName(),nwCreat.getId(),sceneSubnet.getIpVersion(),sceneSubnet.getCidr());

					SubnetImpl subnetImpl= new SubnetImpl();
					Subnet sntt = new Subnet();
					sntt.setsubnetName(sceneSubnet.getSubnetName());
					sntt.setsubnetNetworkId(nwCreat.getId());
					sntt.setsubnetIpVersion(sceneSubnet.getIpVersion());
					if(sceneSubnet.getCidr()!=null)
					{
						sntt.setsubnetCidr(sceneSubnet.getCidr());
					}else if(sceneSubnet.getSubnetpoolId()!=null){
						sntt.setsubnetPoolId(sceneSubnet.getSubnetpoolId());
					}
//					sntt.setsubnetPoolId(sceneSubnet.getSubnetpoolId());
					Subnet sn_new = subnetImpl.createSubnet(sntt);

					subnetMap.put(sceneSubnet.getId(), sn_new.getsubnetId());

					logger.debug("dingh===subnetId" + sn_new.getsubnetId());
				}
				SceneEnvironmentInstanceOs sceneEnvironmentInstanceOs=new SceneEnvironmentInstanceOs();
				sceneEnvironmentInstanceOs.setEnvironmentInstanceId(sceneCtfEnvironmentInstance.getId());
				sceneEnvironmentInstanceOs.setNetworkId(nwCreat.getId());

				sceneCtfEnvironmentInstanceService.envInstanceNetworkInsert(sceneEnvironmentInstanceOs);

			}


			SecuritygroupImpl securitygroupImpl = new SecuritygroupImpl();

			//...
			List<SceneSecurityGroup> sceneSecurityGroupList=sceneSecurityGroupService.findSGListByEnvironmentId(DelFlag.DEL_FLAG_NORMAL,sceneCtfEnvironmentInstance.getId());
			logger.debug("dingh===sceneSecurityGroup="+sceneSecurityGroupList.size());
			for(SceneSecurityGroup sceneSecurityGroup:sceneSecurityGroupList)
			{
				logger.debug("dingh===sceneSecurityGroup=" + sceneSecurityGroup.getName() + " " + sceneSecurityGroup.getRemarks());
				Securitygroup temp=new Securitygroup();
				temp.setSecuritygroupName(sceneSecurityGroup.getName());
				temp.setDescription(sceneSecurityGroup.getRemarks());
				Securitygroup securitygroup = securitygroupImpl.createSecuritygroup(temp);

//				instanceSgList.add(securitygroup.getSecuritygroupId());
				sgMap.put(sceneSecurityGroup.getId(), securitygroup.getSecuritygroupId());

				logger.debug("dingh===sceneSecurityGroupId=" + securitygroup.getSecuritygroupId());

				List<SceneSecurityGroupRule> sceneSecurityGroupRuleList=sceneSecurityGroupRuleService.findSGRListBySecurityGroupId(sceneSecurityGroup);
				logger.debug("dingh===sceneSecurityGroupRuleList.size()=" + sceneSecurityGroupRuleList.size());
				for(SceneSecurityGroupRule sceneSecurityGroupRule:sceneSecurityGroupRuleList)
				{
					logger.debug("dingh===sceneSecurityGroupRule=" + sceneSecurityGroupRule.toString());

					//创建安全组规则
					SecuritygroupRuleImpl srtest = new SecuritygroupRuleImpl();

					SecuritygroupRule srtt = new SecuritygroupRule();
					srtt.setSrDirection(sceneSecurityGroupRule.getDirection());
					srtt.setSrEthertype(sceneSecurityGroupRule.getEthertype());
					srtt.setSrProtocol(sceneSecurityGroupRule.getProtocol());
					srtt.setSrSecurityGroupId(securitygroup.getSecuritygroupId());
					srtt.setSrRemoteGroupId(sceneSecurityGroupRule.getRemoteGroupId());
					if(sceneSecurityGroupRule.getRemoteGroupId()!=null)
					{
						srtt.setSrRemoteGroupId(sceneSecurityGroupRule.getRemoteGroupId());
					}else if(sceneSecurityGroupRule.getRemoteIpPrefix()!=null){
						srtt.setSrRemoteIpPrefix(sceneSecurityGroupRule.getRemoteIpPrefix());
					}
					srtt.setSrPortMax(sceneSecurityGroupRule.getToPort());
					srtt.setSrPortMin(sceneSecurityGroupRule.getFromPort());

					srtest.createSecuritygroupRule(srtt);


//				logger.debug("dingh===sceneSecurityGroupRuleId=" + sr_new.getSrId());
					logger.debug("dingh===安全组规则创建成功");

				}
				SceneEnvironmentInstanceOs sceneEnvironmentInstanceOs=new SceneEnvironmentInstanceOs();
				sceneEnvironmentInstanceOs.setEnvironmentInstanceId(sceneCtfEnvironment.getId());
				sceneEnvironmentInstanceOs.setSecurityGroupId(securitygroup.getSecuritygroupId());

				sceneCtfEnvironmentInstanceService.envInstanceSecurityGroupInsert(sceneEnvironmentInstanceOs);


			}



			//路由
			List<SceneRouter> sceneRouterList=sceneRouterService.findRouterListByEnvironmentId(DelFlag.DEL_FLAG_NORMAL,sceneCtfEnvironment.getId());
			logger.debug("dingh===sceneRouterList=" + sceneRouterList.size());
			for(SceneRouter sceneRouter:sceneRouterList) {
				logger.debug("dingh===sceneRouter=" + sceneRouter.getRouterName());

				RouterImpl routerDemo = new RouterImpl();
				Router router = new Router();
				if(sceneRouter.getRouterName()!=null)
					router.setRouterName(sceneRouter.getRouterName());
				if(sceneRouter.getNetworkId()!=null)
					router.setRouterNetworkId(sceneRouter.getNetworkId());
				Router new_router=routerDemo.createRouter(router);

//				instanceRouterList.add(new_router.getRouterId());

				logger.debug("dingh===RouterId=" + new_router.getRouterId());


				List<SceneSubnet> sceneSubnetList=sceneSubnetService.getRouterSubnetListByRouterId(sceneRouter);
				logger.debug("dingh===RouterSubnetList=" + sceneSubnetList.size());

				//路由接口
				if(sceneSubnetList.size()>0)
				{
					for(SceneSubnet sceneSubnet:sceneSubnetList)
					{
						routerDemo.addRouterInterface(new_router.getRouterId(),subnetMap.get(sceneSubnet.getId()), SceneConstants.routerAndNetwork);
						//添加
						SceneEnvironmentInstanceOs sceneEnvironmentInstanceOs=new SceneEnvironmentInstanceOs();
						sceneEnvironmentInstanceOs.setEnvironmentInstanceId(sceneCtfEnvironment.getId());
						sceneEnvironmentInstanceOs.setRouterId(new_router.getRouterId());
						sceneEnvironmentInstanceOs.setSubnetId(subnetMap.get(sceneSubnet.getId()));

						sceneCtfEnvironmentInstanceService.envInstanceRouterInsert(sceneEnvironmentInstanceOs);

					}
				}else {
					SceneEnvironmentInstanceOs sceneEnvironmentInstanceOs=new SceneEnvironmentInstanceOs();
					sceneEnvironmentInstanceOs.setEnvironmentInstanceId(sceneCtfEnvironmentInstance.getId());
					sceneEnvironmentInstanceOs.setRouterId(new_router.getRouterId());

					sceneCtfEnvironmentInstanceService.envInstanceRouterInsert(sceneEnvironmentInstanceOs);
				}


				//路由端口
				List<ScenePort> routerPortList=scenePortService.findRouterPortList(sceneRouter.getId());
				if(routerPortList.size()>0)
				{
					for(ScenePort routerPort:routerPortList)
					{
						PortImpl portImpl=new PortImpl();
						Port port =new Port();
						if(routerPort.getName()!=null)
							port.setPortName(routerPort.getName());
						port.setPortNetworkId(networkMap.get(routerPort.getNetworkId()));
						JSONArray fixedIps = new JSONArray();
						JSONObject fixedIp = new JSONObject();
						fixedIp.put("ip_address", routerPort.getFixedIp());
						fixedIps.add(0, fixedIp);
						port.setPortFixedIp(fixedIps);
						Port newPort =portImpl.createPort(port);

						Thread.sleep(1000);
						logger.debug("dingh===路由=端口成功id=" + newPort.getPortId());

						routerDemo.addRouterInterface(new_router.getRouterId(), newPort.getPortId(), SceneConstants.routerAndRouter);
						SceneEnvironmentInstanceOs sceneEnvironmentInstanceOs=new SceneEnvironmentInstanceOs();
						sceneEnvironmentInstanceOs.setEnvironmentInstanceId(sceneCtfEnvironmentInstance.getId());
						sceneEnvironmentInstanceOs.setPortId(newPort.getPortId());
						sceneEnvironmentInstanceOs.setId(new_router.getRouterId());

						sceneCtfEnvironmentInstanceService.envInstancePortInsert(sceneEnvironmentInstanceOs);

					}
				}
				List<SceneRouterTable> routerTableList=sceneRouterService.findRouterTableListByRouterId(sceneRouter.getId());
				logger.debug("dingh===routerTableList=" + routerTableList.size());
				for(SceneRouterTable sceneRouterTable:routerTableList)
				{
					RouterImpl routerdemo = new RouterImpl();
					Router routertt = new Router();
					HashMap<String,String> pp = new HashMap<String,String>();
					pp.put(sceneRouterTable.getDestination(), sceneRouterTable.getNexthop());
					routertt.setRouters(pp);
					Router router_update = routerdemo.updateRouter(new_router.getRouterId(),routertt);
					logger.debug("dingh===增加路由表成功=");

				}

				SceneFirewall sceneFirewall=sceneRouterService.getRouterFirewall(sceneRouter.getId());
				if(sceneFirewall!=null&&!sceneFirewall.equals(""))
				{
					firewallRuleIdList=new ArrayList<>();

					//创建防火墙规则
					List<SceneFirewallRule> sceneFirewallRuleList=sceneRouterService.findFirewallRuleList(sceneFirewall.getId());
					for(SceneFirewallRule sceneFirewallRule:sceneFirewallRuleList)
					{
						logger.debug("dingh===创建防火墙规则==1=");

						FireWallRuleImpl fwrule = new FireWallRuleImpl();
						FireWallRule fwruledemo = new FireWallRule();
						if(sceneFirewallRule.getAction()!=null&&!sceneFirewallRule.getAction().equals(""))
						{
							logger.debug("防火墙规则=sceneFirewallRule.getAction()="+sceneFirewallRule.getAction());
							fwruledemo.setAction(sceneFirewallRule.getAction());
						}
						if(sceneFirewallRule.getProtocol()!=null&&!sceneFirewallRule.getProtocol().equals(""))
						{
							logger.debug("防火墙规则=sceneFirewallRule.getProtocol()="+sceneFirewallRule.getProtocol());
							fwruledemo.setProtocol(sceneFirewallRule.getProtocol());
						}
						if(sceneFirewallRule.getSourceIpAddress()!=null&&!sceneFirewallRule.getSourceIpAddress().equals(""))
						{
							logger.debug("防火墙规则=sceneFirewallRule.getSourceIpAddress()="+sceneFirewallRule.getSourceIpAddress());
							fwruledemo.setSourceIpAddress(sceneFirewallRule.getSourceIpAddress());
						}
						if(sceneFirewallRule.getDestinationIpAddress()!=null&&!sceneFirewallRule.getDestinationIpAddress().equals(""))
						{
							logger.debug("防火墙规则=sceneFirewallRule.getDestinationIpAddress()="+sceneFirewallRule.getDestinationIpAddress());
							fwruledemo.setDestinationIpAddress(sceneFirewallRule.getDestinationIpAddress());
						}
						if(sceneFirewallRule.getName()!=null&&!sceneFirewallRule.getName().equals(""))
						{
							logger.debug("防火墙规则=sceneFirewallRule.getName()="+sceneFirewallRule.getName());
							fwruledemo.setName(sceneFirewallRule.getName());
						}
						if(sceneFirewallRule.getSourcePort()!=null&&!sceneFirewallRule.getSourcePort().equals(""))
						{
							logger.debug("防火墙规则=sceneFirewallRule.getSourcePort()="+sceneFirewallRule.getSourcePort());
							fwruledemo.setSourcePort(sceneFirewallRule.getSourcePort());
						}
						if(sceneFirewallRule.getDestinationPort()!=null&&!sceneFirewallRule.getDestinationPort().equals(""))
						{
							logger.debug("防火墙规则=sceneFirewallRule.getDestinationPort()="+sceneFirewallRule.getDestinationPort());
							fwruledemo.setDestinationPort(sceneFirewallRule.getDestinationPort());
						}
						if(sceneFirewallRule.getIpVersion()!=null&&!sceneFirewallRule.getIpVersion().equals(""))
						{
							logger.debug("防火墙规则=sceneFirewallRule.getIpVersion()="+sceneFirewallRule.getIpVersion());
							fwruledemo.setIpVersion(sceneFirewallRule.getIpVersion());
						}
						FireWallRule newfwrule = fwrule.createFireWallRule(fwruledemo);
						logger.debug("dingh===创建防火墙规则成功=");

						SceneEnvironmentInstanceOs sceneEnvironmentInstanceOs=new SceneEnvironmentInstanceOs();
						sceneEnvironmentInstanceOs.setEnvironmentInstanceId(sceneCtfEnvironmentInstance.getId());
						sceneEnvironmentInstanceOs.setFirewallRuleId(newfwrule.getId());

						sceneCtfEnvironmentInstanceService.envInstanceFirewallRuleInsert(sceneEnvironmentInstanceOs);
						firewallRuleIdList.add(newfwrule.getId());
					}
					//创建防火墙策略
					FireWallPolicyImpl fwpolicy = new FireWallPolicyImpl();
					FireWallPolicy fwpolcydemo = new FireWallPolicy();
					fwpolcydemo.setName(sceneFirewall.getFirewallPolicyName());
					fwpolcydemo.setFirewallRules(firewallRuleIdList);
					FireWallPolicy newPolicy=fwpolicy.createFireWallPolicy(fwpolcydemo);
					logger.debug("dingh===创建防火墙策略成功=");

					//创建防火墙
					FireWallImpl impl = new FireWallImpl();
					FireWall firewall = new FireWall();
					List<String> routerIds = new ArrayList<String>();
					firewall.setName(sceneFirewall.getFirewallName());
					firewall.setFirewallPolicyId(newPolicy.getId());
					routerIds.add(new_router.getRouterId());
					firewall.setRouterIds(routerIds);
					FireWall newfireWall=impl.createFireWall(firewall);
					logger.debug("dingh===创建防火墙成功=");

					SceneEnvironmentInstanceOs sceneEnvironmentInstanceOs=new SceneEnvironmentInstanceOs();
					sceneEnvironmentInstanceOs.setEnvironmentInstanceId(sceneCtfEnvironmentInstance.getId());
					sceneEnvironmentInstanceOs.setFirewallId(newfireWall.getFirewallId());
					sceneEnvironmentInstanceOs.setFirewallPolicyId(newPolicy.getId());

					sceneCtfEnvironmentInstanceService.envInstanceFirewallInsert(sceneEnvironmentInstanceOs);
				}



			}
*/




			//虚拟机
//			List<SceneVmTemplate> sceneVmTemplateList=sceneVmTemplateService.findVMListByEnvironmentId(sceneEnvironment);
//			logger.debug("dingh===sceneVmTemplateList=" + sceneVmTemplateList.size());
			for(SceneVmTemplate sceneVmTemplate:sceneVmTemplateList) {
				logger.debug("dingh===sceneVmTemplate=111" + sceneVmTemplate.getName());
				logger.debug("dingh===虚拟机名称=111" + sceneVmTemplate.getVmName());

				//创建云主机类型
				FlavorsImpl flavorImpl=new FlavorsImpl();
				Flavor flavor =new Flavor();
				String uuid = IdGen.uuid();
				flavor.setFlavorName(sceneVmTemplate.getVmName()+"-"+uuid);
				flavor.setFlavorRam(sceneVmTemplate.getRam());
				flavor.setFlavorVcpus(sceneVmTemplate.getVcpus());
				flavor.setFlavorDisk(sceneVmTemplate.getDisk());
				Flavor reFlavor=flavorImpl.createFlavor(flavor);
				logger.debug("dingh===创建云主机类型成功=" +reFlavor.getFlavorId());

				VirtualMachineImpl nova = new VirtualMachineImpl();
				Server newServer = new Server();
				newServer.setName(sceneVmTemplate.getVmName());
				newServer.setFlavorRef(reFlavor.getFlavorId());
				newServer.setImageRef(sceneVmTemplate.getImageRef());
				logger.debug("dingh===虚拟机=" + sceneVmTemplate.getVmName() + " " + reFlavor.getFlavorId() + " " + sceneVmTemplate.getImageRef());

				JSONArray networks = new JSONArray();
				JSONArray ports = new JSONArray();
				sceneVmTemplate.setEnvironmentId(sceneCtfEnvironment.getId());
				List<SceneNetwork> networkList=sceneNetworkService.findVmNetworkList(sceneVmTemplate);

/**
				logger.debug("dingh===虚拟机=VmNetworkList=" + networkList.size());

				for(int i=0;i<networkList.size();i++)
				{
					logger.debug("dingh===虚拟机=网络id="+networkMap.get(networkList.get(i).getId()));

					JSONObject network1 = new JSONObject();
					network1.put("uuid", networkMap.get(networkList.get(i).getId()));
					networks.add(i, network1);
				}
				//创建端口
				ScenePort scenePort=scenePortService.get(sceneVmTemplate.getPortId());
				List<Port> portList=new ArrayList<>();
				logger.debug("dingh===虚拟机=端口-网络id=" + networkMap.get(scenePort.getNetworkId()));
				logger.debug("dingh===虚拟机=端口-ip=" + scenePort.getFixedIp());

				PortImpl portImpl=new PortImpl();
				Port port =new Port();
				if(scenePort.getName()!=null)
					port.setPortName(scenePort.getName());
				port.setPortNetworkId(networkMap.get(scenePort.getNetworkId()));
				JSONArray fixedIps = new JSONArray();
				JSONObject fixedIp = new JSONObject();
				fixedIp.put("ip_address", scenePort.getFixedIp());
				fixedIps.add(0, fixedIp);
				port.setPortFixedIp(fixedIps);
				Port newPort =portImpl.createPort(port);

				Thread.sleep(1000);
				logger.debug("dingh===虚拟机=端口成功id=" + newPort.getPortId());

				JSONObject port1 = new JSONObject();
				port1.put("port", newPort.getPortId());
				ports.add(0, port1);
//				sceneEnvironmentInstanceService.envInstancePortInsert(sceneEnvironmentInstance.getId(), newPort.getPortId());
				//云主机添加安全组
				JSONArray sgs = new JSONArray();
				List<SceneSecurityGroup> sgList=sceneSecurityGroupService.findVmSgList(sceneVmTemplate);
				for(int i=0;i<sgList.size();i++)
				{
					JSONObject sg = new JSONObject();
					sg.put("name", sgList.get(i).getName());
					sgs.add(i, sg);

				}
				if(sgs.size()>0) {
					logger.debug("dingh===虚拟机-安全组=");

					newServer.setSecurityGroups(sgs);
				}
				if(ports.size()>0) {
					logger.debug("dingh===虚拟机-端口=");

					newServer.setPorts(ports);
				}
				else {
					logger.debug("dingh===虚拟机-网络=");
					if(networks.size()>0)
						newServer.setNetworks(networks);
				}
*/


				JSONObject network1 = new JSONObject();
				network1.put("uuid", SceneConstants.ctfNetworkId);
				networks.add(0, network1);
				newServer.setNetworks(networks);

				System.out.println("newServer   : " + newServer);
				Server reServer = nova.addServer(newServer);
				System.err.println("reServer   : " + reServer);

				vmMap.put(sceneVmTemplate.getId(), reServer.getId());
				logger.debug("dingh===ServerId=" + reServer.getId());

//				instanceVmList.add(reServer.getId());
//				Thread.sleep(5000);
				if(sceneCtfEnvironment.getCtfType().equals("0"))
				{
					//rootDomain = "cubeliving.com.cn";//根域名
					String subDomain = IdGen.uuid();
					Demo demo=new Demo();
					String ip=null;
//					demo.createSubDomain(subDomain,"139.196.48.196","8787");
					try{
						int i=0;
						logger.debug("dingh===虚拟机信息"+reServer.getId()+" "+SceneConstants.ctfNetworkName);
						Server server=nova.getServerById(reServer.getId(),SceneConstants.ctfNetworkName);
						if(server!=null)
							ip=server.getIp();
						while (ip==null)
						{
							Thread.sleep(1000);
							i++;
							if(i>600)
								break;
							logger.debug("dingh===虚拟机信息"+reServer.getId()+" "+SceneConstants.ctfNetworkName);
							server=nova.getServerById(reServer.getId(), SceneConstants.ctfNetworkName);
							if(server!=null)
								ip=server.getIp();
						}
						logger.debug("dingh===虚拟机Ip=" + ip);
						demo.createSubDomain(subDomain, ip, SceneConstants.vhostPort);
						sceneCtfEnvironmentInstance.setLink("http://"+subDomain+"."+SceneConstants.rootDomain);
					}catch (Exception e)
					{
						logger.debug("dingh===获取虚拟机详情失败");
					}

				}
				SceneEnvironmentInstanceOs sceneEnvironmentInstanceOs=new SceneEnvironmentInstanceOs();
				sceneEnvironmentInstanceOs.setEnvironmentInstanceId(sceneCtfEnvironmentInstance.getId());
				sceneEnvironmentInstanceOs.setVmTemplateId(reServer.getId());
				sceneEnvironmentInstanceOs.setIsOperateMachine(sceneVmTemplate.getIsOperateMachine());
/**	930修改		sceneEnvironmentInstanceOs.setPortId(newPort.getPortId());*/

				sceneEnvironmentInstanceOs.setPortId(null);
				sceneEnvironmentInstanceOs.setVmTemplateName(sceneVmTemplate.getName());
				sceneEnvironmentInstanceOs.setVmName(sceneVmTemplate.getVmName());
				sceneEnvironmentInstanceOs.setVmId(sceneVmTemplate.getId());

				sceneEnvironmentInstanceOs.setFlavorRef(reFlavor.getFlavorId());

				instanceVmList.add(sceneEnvironmentInstanceOs);
//				logger.debug("dingh===插入实例Vm=1=");
//				sceneEnvironmentInstanceService.envInstanceVmTemplateInsert(sceneEnvironmentInstanceOs);
//				logger.debug("dingh===插入实例Vm=2=");

//				isOperateList.add(sceneVmTemplate.getIsOperateMachine());

			}


//			List<SceneEnvironmentInstanceOs> vmList=sceneEnvironmentInstanceService.findVmTemplateListByInstanceId(sceneEnvironmentInstance);
//			logger.debug("dingh===vm数量=" + vmList.size());

			System.err.println("************************55555");
			for(int i=0;i<instanceVmList.size();i++)
			{

				if(instanceVmList.get(i).getIsOperateMachine().equals("0"))
				{
					boolean getUrl=true;
					logger.debug("dingh===while="+instanceVmList.get(i).getVmTemplateId());

					while (getUrl)
					{
						VirtualMachineImpl virtualMachineImpl=new VirtualMachineImpl();
						Server server=virtualMachineImpl.getServerById(instanceVmList.get(i).getVmTemplateId(),SceneConstants.ctfNetworkName);

						if(server.getStatus().equals("ACTIVE")||server.getStatus().equals("active"))
						{

							//获取控制台
							ConsolePartImpl showconsoledemo = new ConsolePartImpl();
							ConsoleType consoletype = new ConsoleType();
							consoletype.setType("novnc");

							ConsoleIndex getconsole = showconsoledemo.GetConsole(server.getId(), consoletype);
							logger.debug("dingh===获取控制台" + i + "=" + getconsole.getUrl() + " " + getconsole.getType());
							logger.debug("dingh===更新url" + i + "=" + getconsole.getUrl() + " " + instanceVmList.get(i).getVmTemplateId());
							instanceVmList.get(i).setConsoleUrl(getconsole.getUrl());

							getUrl=false;
						}else if(server.getStatus().equals("ERROR")||server.getStatus().equals("ERROR"))
						{
							logger.debug("dingh===获取控制台失败"+instanceVmList.get(i).getVmTemplateId()+"==="+i);
							getUrl=false;

						}
					}
				}
			}
//			for(int i=0;i<vmList.size();i++) {
//				logger.debug("dingh===更新实例Vm="+vmList.get(i).getVmTemplateId());
//				sceneEnvironmentInstanceService.instanceVmUpdate(instanceVmUrlMap.get(vmList.get(i).getVmTemplateId()), vmList.get(i).getVmTemplateId());
//			}
//			for(int i=0;i<sceneVmTemplateList.size();i++)
//			{
//
//				if(sceneVmTemplateList.get(i).getIsOperateMachine().equals("0"))
//				{
//					boolean getUrl=true;
//					while (getUrl)
//					{
//						logger.debug("dingh===while");
//
//						VirtualMachineImpl virtualMachineImpl=new VirtualMachineImpl();
//						Server server=virtualMachineImpl.getServerById(vmMap.get(sceneVmTemplateList.get(i).getId()));
//						logger.debug("dingh===while1="+server.getStatus());
//
//						if(server.getStatus().equals("ACTIVE")||server.getStatus().equals("active"))
//						{
//
//							//获取控制台
//							ConsolePartImpl showconsoledemo = new ConsolePartImpl();
//							System.out.println("获取控制台" + i);
//
//							ConsoleType consoletype = new ConsoleType();
//
//
//							consoletype.setType("novnc");
//
//
//							ConsoleIndex getconsole = showconsoledemo.GetConsole(server.getId(), consoletype);
//							sceneEnvironmentInstance.setUrl(getconsole.getUrl());
//							sceneEnvironmentInstance.setType(getconsole.getType());
//							logger.debug("dingh===获取控制台"+i+"=" + getconsole.getUrl() + " " + getconsole.getType());
//							sceneEnvironmentInstanceService.instanceVmUpdate(getconsole.getUrl(),vmMap.get(sceneVmTemplateList.get(i).getId()));
//							sceneVmTemplateList.get(i).setConsoleUrl(getconsole.getUrl());
//							vmUrlList.add(sceneVmTemplateList.get(i));
//							System.out.println("sceneVmTemplate.getId()===" + getconsole.getType() + " " + getconsole.getUrl());
//							getUrl=false;
//						}else if(server.getStatus().equals("ERROR")||server.getStatus().equals("ERROR"))
//						{
//							getUrl=false;
//
//						}
//						else {
//							try {
//								Thread.sleep(1000);
//							} catch (InterruptedException e) {
//								e.printStackTrace();
//							}
//						}
//					}
//				}
//			}


		}catch (RuntimeException e){
			System.err.println("************************444" +e);

		}

		System.err.println(sceneCtfEnvironment.getCtfEnvironmentName() +"************************");


//		*********************************************************
		sceneCtfEnvironmentInstance.setCtfEnvironmentName(sceneCtfEnvironment.getCtfEnvironmentName());
//		*********************************************************





		sceneCtfEnvironmentInstance.setCtfEnvironmentId(sceneCtfEnvironment.getId());
		Date data=new Date();

		int envTime=(int)(Double.parseDouble(sceneCtfEnvironment.getCtfEnvironmentTime())*60);
		Calendar ca = Calendar.getInstance();//得到一个Calendar的实例
		ca.setTime(data); //设置时间为当前时间
		ca.set(Calendar.MINUTE, ca.get(Calendar.MINUTE) + envTime);
		Date endDate=ca.getTime();
		sceneCtfEnvironmentInstance.setEndDate(endDate);
		sceneCtfEnvironmentInstance.setUpdateDate(data);
		sceneCtfEnvironmentInstanceService.save(sceneCtfEnvironmentInstance);
		logger.debug("dingh===更新实例：" + sceneCtfEnvironmentInstance.getId());
		for(int i=0;i<instanceVmList.size();i++) {
			logger.debug("dingh===插入实例Vm=" + instanceVmList.get(i).getVmTemplateId());
			logger.debug("dingh===VmUrl=" + instanceVmList.get(i).getConsoleUrl());

			sceneCtfEnvironmentInstanceService.envInstanceVmTemplateInsert(instanceVmList.get(i));
		}
		//定时任务删除实例
//		if(sceneEnvironmentInstance.getAutoDelete().equals("0"))
		instanceScheduleJob(sceneCtfEnvironmentInstance, sceneCtfEnvironment);
	}
	/**
	 * 〈方法的功能描述〉:
	 *定时任务-开始定时任务
	 * @Date	 2016/12/6/11:20
	 * @author  zy
	 * @methodName
	 * @param
	 * @return
	 **/
	@Transactional(readOnly = false)
	public void instanceScheduleJob(SceneCtfEnvironmentInstance sceneCtfEnvironmentInstance,SceneCtfEnvironment sceneCtfEnvironment) throws Exception{
		logger.debug("dingh===定时任务开始=="+sceneCtfEnvironmentInstance.getId());
		logger.debug("dingh===定时任务开始=" + sceneCtfEnvironmentInstance.getCreateDate()+" "+sceneCtfEnvironment.getCtfEnvironmentTime());
		logger.debug("dingh===定时任务开始");

		int time=(int)(Double.parseDouble(sceneCtfEnvironment.getCtfEnvironmentTime()) * 60);
		logger.debug("dingh===定时任务开始time=" + time);

		if(time>0)
		{
			//加定时任务
			ScheduleJob scheduleJob = new ScheduleJob();
			scheduleJob.setJobName(sceneCtfEnvironmentInstance.getId());
			scheduleJob.setJobGroup("env_instance");
			scheduleJob.setBeanClass("com.lczyfz.istep.modules.scene.service.SceneCtfEnvironmentService");
			scheduleJob.setBeanName("sceneCtfEnvironmentService");
			scheduleJob.setMethodName("deleteInstance");
			scheduleJob.setCronExpression(getCancelTime(sceneCtfEnvironmentInstance.getUpdateDate(),time));
			scheduleJob.setStartDate(getCancelTimeByDate(sceneCtfEnvironmentInstance.getUpdateDate(),time));
			scheduleJob.setIsConcurrent("1");
			scheduleJob.setStatus(JobStatus.Running.getValue());
			scheduleJob.setIsFactory(JobIsFactoryType.Factory.getValue());
			scheduleJobService.addTask(scheduleJob);
		}


	}
	/**
	 * 〈方法的功能描述〉:
	 *定时任务-消除实例
	 * @Date	 2016/12/6/11:20
	 * @author  zy
	 * @methodName
	 * @param
	 * @return
	 **/
	@Transactional(readOnly = false)
	public void deleteInstance(ScheduleJob scheduleJob) throws Exception{
		logger.debug("dingh===定时任务结束");

		logger.debug("dingh===定时任务结束"+scheduleJob.getId()+" "+scheduleJob.getStatus());

		SceneCtfEnvironmentInstance sceneCtfEnvironmentInstance=sceneCtfEnvironmentInstanceService.get(scheduleJob.getJobName());
		logger.debug("dingh===定时任务结束==" + sceneCtfEnvironmentInstance.getId());
		scheduleJob.setStatus(JobStatus.Stopped.getValue());
		scheduleJobService.save(scheduleJob);
		sceneCtfEnvironmentInstanceService.deleteInstance(sceneCtfEnvironmentInstance);
//		sceneEnvironmentInstanceService.delete(sceneEnvironmentInstance);



//		scheduleJobService.deleteScheduleJobDao(scheduleJob);
		//dingh===获取控制台http://59.77.236.116:6080/vnc_auto.html?token=3108b70c-eab4-4d66-a926-5cc43192baf2
		//dingh===获取控制台http://59.77.236.116:6080/vnc_auto.html?token=0e516aec-b70b-4d9b-9f71-2947c18a11e4


	}
	/**
	 * 〈方法的功能描述〉:
	 *获取取消订单的定时任务的时间
	 * @Date	 2016/12/6/11:22
	 * @author  dingh
	 * @methodName
	 * @param
	 * @return
	 **/

	public String getCancelTime(Date orderTime,int afterMinute){
		Calendar ca = Calendar.getInstance();//得到一个Calendar的实例
		ca.setTime(orderTime); //设置时间为当前时间
		ca.set(Calendar.MINUTE, ca.get(Calendar.MINUTE) + afterMinute);
		Date time = ca.getTime(); //结果
		int year = ca.get(Calendar.YEAR);//获取年份
		int month=ca.get(Calendar.MONTH)+1;//获取月份
		int day=ca.get(Calendar.DATE);//获取日
		int hour=ca.get(Calendar.HOUR_OF_DAY);//小时
		int minute=ca.get(Calendar.MINUTE);//分
		int second=ca.get(Calendar.SECOND);//秒
		//"30 10 1 20 10 ? 2011" 2011年10月20号1点10分30秒触发任务
		String cancelTime=second+" "+minute+" "+hour+" "+day+" "+month+" "+"? "+year;
		return cancelTime;

	}
	public Date getCancelTimeByDate(Date orderTime,int afterMinute){
		Calendar ca = Calendar.getInstance();//得到一个Calendar的实例
		ca.setTime(orderTime); //设置时间为当前时间
		ca.set(Calendar.MINUTE, ca.get(Calendar.MINUTE) + afterMinute);
//		ca.add(Calendar.SECOND, +30);
		Date time = ca.getTime(); //结果
		return time;
	}
	public SceneCtfEnvironment findCtfEnvironmentByName(String name,String DEL_FLAG_NORMAL)
	{
		return dao.findCtfEnvironmentByName(name,DEL_FLAG_NORMAL);
	}

}